package com.skydoves.chatgpt.feature.chat.ddd.bots

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.skydoves.chatgpt.core.data.repository.AppUserRepository
import com.skydoves.chatgpt.core.model.network.CreateBotResponse
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.launch
import javax.inject.Inject

sealed interface UiState {
  data object Nothing : UiState

  data object Loading : UiState
}



@HiltViewModel
class CreateBotViewModel @Inject constructor(
  private val userRepository: AppUserRepository,
  private val uidFlow: Flow<String>,
) :ViewModel(){
  var uid = "null"

  private val createMutableState =
    MutableStateFlow<UiState>(UiState.Nothing)
  val createState: StateFlow<UiState> = createMutableState

  fun getRealUid(onSuccess: (String) -> Unit){
    viewModelScope.launch {
      uid = uidFlow.firstOrNull() ?: return@launch
      onSuccess(uid)
    }
  }

  fun createBot(
    username: String,
    botName: String,
    botDescription:String,
    prompt:String,
    onSuccess: (CreateBotResponse)->Unit
  ){
    createMutableState.value=UiState.Loading
    viewModelScope.launch{
      try {
        val response = userRepository.createBot(username,botName,botDescription,prompt)

        if (response != null) { // 判断 response 是否不为空
          onSuccess(response)
          createMutableState.value=UiState.Nothing
        } else {
          createMutableState.value=UiState.Nothing
          println("Error: Received null response from chat API")
        }
      } catch (e: Exception) {
        createMutableState.value=UiState.Nothing
        println("Error: ${e.localizedMessage}")
      }
    }

  }

}